<?php
/**
 * Created by PhpStorm.
 * 数据导出类
 * User: 李洋波
 * Date: 2016/10/31
 * Time: 17:42
 */

class exportData extends CI_Controller{
    function __construct()
    {
        parent::__construct();
        //加载模型
        $this->load->model('mt_report_model','reportModel');
    }
    //------------------------------------------------------导出维修产品费用数据---------------------------------------
    /**
     * 导出维修产品费用数据
     */
    public function ExportMaintainPriceData(){
        $gp=gp();
        if($gp['startTime']){
            $startTime=strtotime($gp['startTime']);
        }
        if($gp['endTime']){
            $endTime=strtotime($gp['endTime']);
        }
        $excelData=$this->GetNewMaintainPriceData($startTime,$endTime,$gp['platformMerchant'],$gp['brandMerchant'],$gp['point'],$gp['productStatus'],$gp['brand_id'],$gp['model_id']);
        $fieldData=array(
            'order_num'=>'订单号',
            'id'=>'产品ID',
            'service_type'=>'订单类型',
            'category_id'=>'产品类型',
            'brand_warranty'=>'品牌质保',
            'seller_warranty'=>'商家质保',
            'inWarranty_qc'=>'拆包质保',
            'inWarranty'=>'维修质保',
            'statusName'=>'产品状态',
            'payment_date'=> '支付时间',
            'finish_time'=>'完成时间',
            'create_time'=>'创建时间',
            'totalAmount'=>'总计',
            'totalAmountCNY'=>'总计(CNY)',
            'laborAmountIndividualUser'=>'个人手工费',
            'laborAmountIndividualUserCNY'=>'个人手工费(CNY)',
            'laborAmountMerchant'=>'商家手工费',
            'laborAmountMerchantCNY'=>'商家手工费(CNY)',
            'laborAmountBrand'=>'品牌手工费',
            'laborAmountBrandCNY'=>'品牌手工费(CNY)',
            'taxFee'=>'个人税费',
            'taxFeeCNY'=>'个人税费(CNY)',
            'partsAmountBrand'=>'品牌配件费',
            'partsAmountBrand(CNY)'=>'品牌配件费(CNY)',
            'partsAmountIndividualUser'=>'个人配件费',
            'partsAmountIndividualUserCNY'=>'个人配件费(CNY)',
            'partsAmountMerchant'=>'商家配件费',
            'partsAmountMerchantCNY'=>'商家配件费(CNY)',
            'shippingFeeAmountBrand'=>'品牌运费',
            'shippingFeeAmountBrandCNY'=>'品牌运费(CNY)',
            'shippingFeeAmountMerchant'=>'商家运费',
            'shippingFeeAmountMerchantCNY'=>'商家运费(CNY)',
            'shippingFeeAmountIndividualUser'=>'个人运费',
            'shippingFeeAmountIndividualUserCNY'=>'个人运费(CNY)',
            'customers_id'=>'OMS客户ID',//支付客户ID
            'customers_name'=>'客户名称',//支付客户名称
            'sap_id'=>'SAP客户ID',
            'manager_name'=>'客户经理',
            'clearing_type'=>'财务结算类型',
            'payment_type'=>'扣款方式',
            'brandCustomerNum'=>'品牌客户',
            'merchant_num'=>'电商客户',
            'payType'=>'散客支付类型',
            'bank_subject'=>'银行科目',
            'pickup_service'=>'收货方式',
            'shipinTrack'=>'收货追踪号',
            'delivery_service'=>'送货方式',
            'shipoutTrack'=>'发货追踪号',
            'currency_code'=>'货币代码',
            'point'=>'来源网站',
            'name'=>'配件名',
            'sku'=>'配件SKU',
            'price'=>'配件是否需要核销',
            'cost_price'=>'配件成本',
        );
        if($excelData) {
            //gsh_output($excelData);
            //excel_output('MaintainPriceData'.$gp['startTime'].'_'.$gp['endTime'],$fieldData,$excelData);
            ExportCsv($excelData,$fieldData,'MaintainPriceData'.$gp['startTime'].'_'.$gp['endTime']);
        }else{
            redirect(blang_url('maintainReport/maintainReport/ExportDataList?data=1'));
        }
    }

    /**
     * 获取新系统维修产品费用数据
     * @param $startTime
     * @param $endTime
     * @param string $platformMerchant
     * @param string $brandMerchant
     * @param string $point
     * @param string $productStatus
     * @param string $brand_id
     * @param string $model_id
     * @return array
     */
    public function GetNewMaintainPriceData($startTime,$endTime,$platformMerchant='',$brandMerchant='',$point='',$productStatus='',$brand_id='',$model_id=''){
        $exportData=array();//导出数据
        for($i=0;$i<=1000;$i++) {
            //获取新产品数据
            $productNewData = $this->reportModel->GetNewProduct($startTime, $endTime, $platformMerchant, $brandMerchant, $point, $productStatus,$brand_id,$model_id,$i*100,100);
            if($productNewData) {
                $inWarranty = array('保外', '保内');
                $clearing_type=array(1=>'月结客户',2=>'预充值');
                $payment_type=array(1=>'现金',2=>'银行');
                $pickup_service=array('上门取件','客户自付');
                $delivery_service=array('客户自提','快递');
                $service_type=array(1=>'维修',2=>'退货',3=>'翻新',4=>'返修',5=>'检测',6=>'购买配件',7=>'转运');
                //构建新产品数据
                foreach ($productNewData as $prow) {
                    $data = array();//结构数组
                    $pidArray[] = $prow['id'];
                    $pidC=array_count_values($pidArray);
                    $rate=$this->getRate(trim(strtoupper($prow['currency_code_order'])));
                    if ($pidC[$prow['id']] <= 1) {
                        //品牌质保判断
                        if ($prow['inWarranty_qc'] == 0 || $prow['inWarranty'] == 0) {
                            $brand_warranty = '保外';
                        } else {
                            $brand_warranty = '保内';
                        }
                        /*//完成时间判断
                        if(in_array($prow['status_id'],array(13,17))){
                            $finish_time=date('Y-m-d H:i:s', $prow['add_time']);
                        }else{
                            $finish_time='';
                        }*/
                        //判断支付客户
                        if ($prow['laborAmountBrand']) {
                            $cInfo = $this->reportModel->getCustomersInfo($prow['brandCustomerNum']);
                        } else {
                            $cInfo = $this->reportModel->getCustomersInfo($prow['merchant_num']);
                        }
                        //付款方式
                        $dInfo = $this->reportModel->getDepositRecord($prow['order_num']);
                        //散客支付类型
                        $sInfo = $this->reportModel->getPaymentRecord($prow['consumer_num']);
                        //产品类型
                        $pType = $this->common_model->selectFirst('mt_product_category', array('id' => $prow['category_id']));
                        //获取拒绝报价轨迹
                        $getNAQ = $this->reportModel->getNAQ($prow['id'], 7);
                        //数据重构
                        $data['order_num'] = $prow['order_num'];
                        $data['id'] = $prow['id'];
                        $data['service_type'] = $service_type[$prow['service_type']];
                        $data['category_id'] = $pType['name_ch'];
                        $data['brand_warranty'] = $brand_warranty;
                        $data['seller_warranty'] = $inWarranty[$prow['seller_warranty']];
                        $data['inWarranty_qc'] = $inWarranty[$prow['inWarranty_qc']];
                        $data['inWarranty'] = $inWarranty[$prow['inWarranty']];
                        $data['statusName'] = $this->reportModel->GetStatusName($prow['status_id']);
                        $data['payment_date'] = $prow['payment_date'] ? date('Y-m-d H:i:s', $prow['payment_date']) : '';
                        $data['finish_time'] = date('Y-m-d H:i:s',$prow['track_time']);
                        $data['create_time'] = $prow['create_time'];
                        $data['totalAmount'] = $getNAQ['end_sid'] ? $prow['NAQAmount'] : $prow['totalAmount'];
                        if ($prow['service_type'] == 4) {
                            $data['totalAmount'] = 0;
                        }
                        $data['totalAmountCNY']=$data['totalAmount']*$rate;
                        $data['laborAmountIndividualUser'] = $prow['laborAmountIndividualUser'];
                        $data['laborAmountIndividualUserCNY']=$data['laborAmountIndividualUser']*$rate;
                        $data['laborAmountMerchant'] = $prow['laborAmountMerchant'];
                        $data['laborAmountMerchantCNY'] = $prow['laborAmountMerchant']*$rate;
                        $data['laborAmountBrand'] = $prow['laborAmountBrand'];
                        $data['laborAmountBrandCNY'] = $prow['laborAmountBrand']*$rate;
                        $data['taxFee'] = $prow['taxFee'];
                        $data['taxFeeCNY'] = $prow['taxFee']*$rate;
                        $data['partsAmountBrand'] = $prow['partsAmountBrand'];
                        $data['partsAmountBrandCNY'] = $prow['partsAmountBrand']*$rate;
                        $data['partsAmountIndividualUser'] = $prow['partsAmountIndividualUser'];
                        $data['partsAmountIndividualUserCNY'] = $prow['partsAmountIndividualUser']*$rate;
                        $data['partsAmountMerchant'] = $prow['partsAmountMerchant'];
                        $data['partsAmountMerchantCNY'] = $prow['partsAmountMerchant']*$rate;
                        $data['shippingFeeAmountBrand'] = $prow['shippingFeeAmountBrand'];
                        $data['shippingFeeAmountBrandCNY'] = $prow['shippingFeeAmountBrand']*$rate;
                        $data['shippingFeeAmountMerchant'] = $prow['shippingFeeAmountMerchant'];
                        $data['shippingFeeAmountMerchantCNY'] = $prow['shippingFeeAmountMerchant']*$rate;
                        $data['shippingFeeAmountIndividualUser'] = $prow['shippingFeeAmountIndividualUser'];
                        $data['shippingFeeAmountIndividualUserCNY'] = $prow['shippingFeeAmountIndividualUser']*$rate;
                        $data['consumer_num'] = $cInfo['id'];
                        $data['consumer_name'] = $cInfo['name'];
                        $data['sap_id'] = $cInfo['sap_id'];
                        $data['manager_name'] = $cInfo['manager_name'];
                        $data['clearing_type'] = $clearing_type[$cInfo['clearing_type']];
                        $data['payment_type'] = $payment_type[$dInfo['payment_type']];
                        $data['brandCustomerNum'] = $this->reportModel->GetCline($prow['brandCustomerNum']);
                        $data['merchant_num'] = $this->reportModel->GetCline($prow['merchant_num']);
                        $data['payType'] = $sInfo['payType'];
                        $data['bank_subject'] = $dInfo['bank_subject'];
                        $data['pickup_service'] = $pickup_service[$prow['pickup_service']];
                        $data['shipinTrack'] = $prow['shipinTrack'];
                        $data['delivery_service'] = $delivery_service[$prow['delivery_service']];
                        $data['shipoutTrack'] = $prow['shipoutTrack'];
                        $data['currency_code'] = $prow['currency_code_order'];
                        $data['point'] = $prow['point'];
                        //新配件数据
                        $newParts = $this->reportModel->GetNewParts($prow['id']);
                        if ($newParts) {
                            foreach ($newParts as $key => $val) {
                                $data['name'] = $val['name'];
                                $data['sku'] = $val['sku'];
                                $data['quantity'] = $val['quantity'];
                                $data['cost_price'] = $val['cost_price'];
                                //$data['price'] = $val['quantity'] * $val['price'];
                                if ($key > 0) {
                                    $data['totalAmount'] = '';
                                    $data['laborAmountIndividualUser'] = '';
                                    $data['laborAmountMerchant'] = '';
                                    $data['laborAmountBrand'] = '';
                                    $data['taxFee'] = '';
                                    $data['partsAmountBrand'] = '';
                                    $data['partsAmountIndividualUser'] = '';
                                    $data['partsAmountMerchant'] = '';
                                    $data['shippingFeeAmountBrand'] = '';
                                    $data['shippingFeeAmountMerchant'] = '';
                                    $data['shippingFeeAmountIndividualUser'] = '';
                                    $data['name'] = $val['name'];
                                    $data['sku'] = $val['sku'];
                                    $data['quantity'] = $val['quantity'];
                                    $data['cost_price'] = $val['cost_price'];
                                }
                                $exportData[] = $data;
                            }
                        } else {
                            $exportData[] = $data;
                        }
                    }
                }
            }else{
                break;
            }
            usleep(100);
        }
        return $exportData;
    }
    //------------------------------------------------------导出商家维修数据----------------------------------
    /**
     * 导出商家订单数据
     */
    public function ExportMerchantOrderData(){
        set_time_limit(0);
        $gp=gp();
        $exportData=array();
        $data=$this->GetMerchantOrderData($gp['platformMerchant'],$gp['point'],$gp['brandMerchant'],$gp['startTime'],$gp['endTime']);
        $exportData[0]['fieldData']=array(
            'order_num'=>'订单号',
            'merchant_num'=>'电商',
            'point'=>'站点',
            'service_type'=>'服务类型',
            'storeOrShip'=>'处理方式',
            'product_brand'=>'产品品牌',
            'product_model'=>'型号',
            'create_time'=>'建单时间',
            'receiving_time'=>'收货(时间)',
            'test_repair_time'=>'检测完成_待维修（时间）',
            'their_repair_time'=>'接单维修（时间）',
            'to_quote_time'=>'待报价（时间）',
            'quote_time'=>'报价（时间）',
            'quote_ok_time'=>'同意报价（时间）',
            'disagree_time'=>'拒绝报价（时间）',
            'await_parts_time'=>'维修中等待配件（时间）',
            'repair_ing_time'=>'维修中（时间）',
            'repair_ok_time'=>'维修完成（时间）',
            'test_start_time_diff'=>'已收货到开始检测工作日数',
            'repair_start_time_diff'=>'检测到开始维修工作日数',
            'toQuote_quote_time_diff'=>'待报价到已报价处理工作日数',
            'quote_ok_time_diff'=>'确认报价工作日数',
            'await_parts_time_diff'=>'等待配件工作日数',
            'test_repairOk_time_diff'=>'接单到维修完成工作日数',
            'test_status_time_diff'=>'接单到当前状态工作日数',
            'status_name'=>'当前状态',
            'repairItem'=>'维修项',
            'grade'=>'维修级别',
            'parts'=>'配件项',
            'fault'=>'故障项',
            'inWarranty'=>'质保类型',
        );
        $exportData[0]['infoData']=$data['exportData'];//全部数据
        $exportData[0]['sheet']='订单明细';

        //保内外维修项数据明细
        $exportData[1]['fieldData']=array('brand'=>'品牌','model'=>'机型','num'=>'数量',
                          'rate'=>'占比','warrantyType'=>'保内Y/保外N','repairItemY'=>'保内维修项',
                          'repairItemN'=>'保外维修项');
        $modelArray=$this->CreateBrandDetailData($data['modelArray']);
        ksort($modelArray);//品牌明细数据
        $exportData[1]['infoData']=$modelArray;
        $exportData[1]['sheet']='保内外维修项数据明细';

        //综合统计
        $exportData[2]['fieldData']=array('待接单','维修中','维修完成','合计/平均历时');
        $exportData[2]['infoData']=$this->CreateServiceReportData($data['countArray']);//综合统计数据
        $exportData[2]['sheet']='维修报告';

        //品牌占比
        $exportData[3]['fieldData']=array('brand'=>'品牌','totalNum'=>'数量','totalRate'=>'占比',
            'yNum'=>'保内数量','yRate'=>'保内占比','nNum'=>'保外数量','nRate'=>'保外占比',
            'repairItem'=>'维修项');
        $brandArray=$this->CreateBrandRateData($data['brandArray']);
        arsort($brandArray);//品牌占比数据
        $exportData[3]['infoData']=$brandArray;
        $exportData[3]['sheet']='维修品牌占比';
        //品牌商需要导出额外两份数据
        //if($gp['brandMerchant']) {
            //维修项占比
            $exportData[4]['fieldData'] = array('model' => '型号', 'repairName' => '维修项', 'num' => '数量', 'rate' => '占比');
            $repairArray = $this->CreateRepairItemData($data['repairArray']);
            ksort($repairArray);
            $exportData[4]['infoData'] = $repairArray;
            $exportData[4]['sheet'] = '维修项占比';

            //配件占比
            $exportData[5]['fieldData'] = array('model' => '型号', 'partsName' => '配件名称', 'num' => '数量', 'rate' => '占比');
            $partsArray = $this->CreatePartsRateData($data['partsArray']);
            ksort($partsArray);
            $exportData[5]['infoData'] = $partsArray;
            $exportData[5]['sheet'] = '配件占比';
            //故障项占比
            $exportData[6]['fieldData'] = array('model' => '型号', 'faultName' => '故障项', 'num' => '数量', 'rate' => '占比');
            $faultArray = $this->CreateFaultRateData($data['faultArray']);
            ksort($faultArray);
            $exportData[6]['infoData'] = $faultArray;
            $exportData[6]['sheet'] = '故障项占比';
        //保内外故障项数据明细
        $exportData[7]['fieldData']=array('brand'=>'品牌','model'=>'机型','num'=>'数量',
            'rate'=>'占比','warrantyType'=>'保内Y/保外N','faultY'=>'保内故障项',
            'faultN'=>'保外故障项');
        $faultDetailArray=$this->CreateFaultDetailData($data['faultDetailArray']);
        ksort($faultDetailArray);
        $exportData[7]['infoData']=$faultDetailArray;
        $exportData[7]['sheet']='保内外故障项数据明细';
        //}
        //导出Excel
        $this->ExportExcel($exportData);
    }

    /**
     * 获取商家订单数据
     * @param $merchant_id
     * @param $point
     * @param $brandCustomerNum
     * @param string $startTime
     * @param string $endTime
     * @return mixed
     */
    public function GetMerchantOrderData($merchant_id,$point,$brandCustomerNum,$startTime='',$endTime=''){
        $exportData=array();//详情导出数组
        $countArray=$this->InitCountArray();//初始化统计数组
        $modelArray=array();//型号统计数组
        $brandArray=array();//品牌统计数组
        $faultDetailArray=array();//故障明细统计数组
        $repairArray=array();//维修项统计数组
        $partsArray=array();//配件统计数组
        $faultArray=array();//故障项统计数组
        $waitReceiveArray=array(1);//待接单判断数组
        $repairIngArray=array(2,3,4,5,6,7,8,9,10,11,12,14,15,16,18);//维修中判断数组
        $repairOkArray=array(13,17);//维修完成判断数组
        $warrantyType = array('保外', '保内');//小数据导出用的 避开查表
        $storeOrShip =array('入库','发货','店铺取件');//发货or入库
        $serviceType = array('1'=>'维修', '2'=>'退货','3'=>'翻新','4'=>'返修','5'=>'检测','6'=>'购买配件');//小数据导出用的 避开查表
        //避免大数据锁表 采用延迟查询 最大10W级数据
        for($i=0;$i<=1000;$i++) {
            $data = $this->reportModel->GetMerchantOrderData($merchant_id,$point,$brandCustomerNum,$startTime,$endTime,$i*100,100);
            if($data) {
                foreach ($data as &$row) {
                    $row['status_name'] = $this->reportModel->GetStatusName($row['status_id']);
                    $inWarranty=$row['inWarranty']==''?1:$row['inWarranty'];
                    $row['inWarranty'] = $warrantyType[$row['inWarranty']];
                    $row['service_type'] = $serviceType[$row['service_type']];
                    $row['storeOrShip']= $storeOrShip[$row['storeOrShip']];
                    $row['merchant_num'] = $this->reportModel->GetCustomerInfo($row['merchant_num']);
                    $repairItem=$this->reportModel->GetRepairItemStr($row['repairItem']);
                    $row['repairItem'] = $repairItem['str'];
                    $row['grade'] = $repairItem['gradeStr'];
                    $parts = $this->reportModel->GetPartsStr($row['id']);
                    $row['parts'] = $parts['str'];
                    $fault=$this->reportModel->GetFault($row['fault']);
                    $row['fault'] = $fault['str'];
                    $trackData = $this->StructureProductTrack($row['id'], $row['add_time']);
                    //摒弃 防止对空值要做处理
                    //$row=array_merge($row,$trackData);
                    $row['receiving_time'] = $trackData['receiving_time'];
                    $row['test_repair_time'] = $trackData['test_repair_time'];
                    $row['their_repair_time'] = $trackData['their_repair_time'];
                    $row['to_quote_time'] = $trackData['to_quote_time'];
                    $row['quote_time'] = $trackData['quote_time'];
                    $row['quote_ok_time'] = $trackData['quote_ok_time'];
                    $row['disagree_time'] = $trackData['disagree_time'];
                    $row['await_parts_time'] = $trackData['await_parts_time'];
                    $row['repair_ing_time'] = $trackData['repair_ing_time'];
                    $row['repair_ok_time'] = $trackData['repair_ok_time'];
                    //因为日期取的是浮点数 在去除双休日后 可能存在负值情况  需要转成0
                    $row['test_start_time_diff'] = $trackData['test_start_time_diff']>0?$trackData['test_start_time_diff']:0;
                    $row['repair_start_time_diff'] = $trackData['repair_start_time_diff']>0?$trackData['repair_start_time_diff']:0;
                    $row['toQuote_quote_time_diff'] = $trackData['toQuote_quote_time_diff']>0?$trackData['toQuote_quote_time_diff']:0;
                    $row['quote_ok_time_diff'] = $trackData['quote_ok_time_diff']>0?$trackData['quote_ok_time_diff']:0;
                    $row['await_parts_time_diff'] = $trackData['await_parts_time_diff']>0?$trackData['await_parts_time_diff']:0;
                    $row['test_repairOk_time_diff'] = $trackData['test_repairOk_time_diff']>0?$trackData['test_repairOk_time_diff']:0;
                    $row['test_status_time_diff'] = $trackData['test_status_time_diff']>0?$trackData['test_status_time_diff']:0;
                    //计算接单(检测完成待维修)到当前导出时间
                    if($row['test_status_time_diff']===0 && $row['test_repair_time']){
                        $weekendDay = $this->GetWeekendDay(date('Y-m-d H:i:s',time()),$row['test_repair_time']);
                        $row['test_status_time_diff']=round((time()-strtotime($row['test_repair_time']))/(3600*24),1)-$weekendDay;
                    }
                    //计算接单(已收货)到当前导出时间
                    if($row['test_status_time_diff']===0 && $row['receiving_time']){
                        $weekendDay = $this->GetWeekendDay(date('Y-m-d H:i:s',time()),$row['receiving_time']);
                        $row['test_status_time_diff']=round((time()-strtotime($row['receiving_time']))/(3600*24),1)-$weekendDay;
                    }
                    //品牌,型号,故障,配件,统计
                    if(!in_array($row['status_id'],$waitReceiveArray)) {
                        //品牌统计
                        $brandArray['total']++;
                        $brandArray[strtolower($row['product_brand'])][$inWarranty ? 'Y' : 'N']['num']++;
                        if($row['repairItem']) {
                            $brandArray[strtolower($row['product_brand'])][$inWarranty ? 'Y' : 'N']['repairItem'][] = $row['repairItem'];
                        }
                        //维修项统计
                        $modelArray['total']++;
                        $modelArray[strtolower($row['product_brand'])][$inWarranty ? 'Y' : 'N'][strtolower($row['product_model'])]['num']++;
                        if($row['repairItem']) {
                            $modelArray[strtolower($row['product_brand'])][$inWarranty ? 'Y' : 'N'][strtolower($row['product_model'])]['repairItem'][] = $row['repairItem'];
                        }
                        //故障项统计
                        $faultDetailArray['total']++;
                        $faultDetailArray[strtolower($row['product_brand'])][$inWarranty ? 'Y' : 'N'][strtolower($row['product_model'])]['num']++;
                        if($row['fault']){
                            $faultDetailArray[strtolower($row['product_brand'])][$inWarranty ? 'Y' : 'N'][strtolower($row['product_model'])]['fault'][] = $row['fault'];
                        }
                        //如果是统计品牌客户 需要统计故障和配件占比
                        //if($brandCustomerNum) {
                        //维修项占比
                            foreach ($repairItem['data'] as $f) {
                                $repairArray[strtolower($row['product_model'])]['total']++;
                                $repairArray[strtolower($row['product_model'])][$f['id']]['num']++;
                                $repairArray[strtolower($row['product_model'])][$f['id']]['name'] = $f['name_ch'];
                            }
                        //配件项占比
                            foreach ($parts['data'] as $p) {
                                $partsArray[strtolower($row['product_model'])]['total']++;
                                $partsArray[strtolower($row['product_model'])][$p['id']]['num']++;
                                $partsArray[strtolower($row['product_model'])][$p['id']]['name'] = $p['name'];
                            }
                        //故障项占比
                        foreach ($fault['data'] as $t) {
                            $faultArray[strtolower($row['product_model'])]['total']++;
                            $faultArray[strtolower($row['product_model'])][$t['id']]['num']++;
                            $faultArray[strtolower($row['product_model'])][$t['id']]['name'] = $t['name_ch'];
                        }

                       // }
                    }
                    //综合数据统计
                    if(in_array($row['status_id'],$waitReceiveArray)){
                        $countArray['WaitReceive_num']++;//待接单量
                    }
                    if(in_array($row['status_id'],$repairIngArray)){
                        $countArray['RepairIng_num']++;//维修中量
                        $countArray['RepairIng_time']+=$row['test_status_time_diff'];//维修中时长
                    }
                    if(in_array($row['status_id'],$repairOkArray)){
                        $countArray['RepairOK_num']++;//维修完成量
                        $countArray['RepairOK_time']+=$row['test_status_time_diff'];//维修完时长
                    }
                    //维修中详细数据统计
                    switch($row['status_id']){
                        case '2':
                            $countArray['TestRepair_num']++;
                            $countArray['TestRepair_time']+=$row['test_status_time_diff'];
                            break;
                        case '3':
                            $countArray['RepairAssigned_num']++;
                            $countArray['RepairAssigned_time']+=$row['test_status_time_diff'];
                            break;
                        case '4':
                            $countArray['WaitQuote_num']++;
                            $countArray['WaitQuote_time']+=$row['test_status_time_diff'];
                            break;
                        case '5':
                            $countArray['PriceQuoted_num']++;
                            $countArray['PriceQuoted_time']+=$row['test_status_time_diff'];
                            break;
                        case '6':
                            $countArray['Agree_num']++;
                            $countArray['Agree_time']+=$row['test_status_time_diff'];
                            break;
                        case '7':
                            $countArray['Disagree_num']++;
                            $countArray['Disagree_time']+=$row['test_status_time_diff'];
                            break;
                        case '8':
                            $countArray['WaitParts_num']++;
                            $countArray['WaitParts_time']+=$row['test_status_time_diff'];
                            break;
                        case '9':
                            $countArray['Repairing_num']++;
                            $countArray['Repairing_time']+=$row['test_status_time_diff'];
                            break;
                        case '10':
                            $countArray['RWaitQC_num']++;
                            $countArray['RWaitQC_time']+=$row['test_status_time_diff'];
                            break;
                        case '11':
                            $countArray['QC_num']++;
                            $countArray['QC_time']+=$row['test_status_time_diff'];
                            break;
                        case '12':
                            $countArray['WaitInStock_num']++;
                            $countArray['WaitInStock_time']+=$row['test_status_time_diff'];
                            break;
                        case '14':
                            $countArray['WaitShip_num']++;
                            $countArray['WaitShip_time']+=$row['test_status_time_diff'];
                            break;
                        case '15':
                            $countArray['TWaitQC_num']++;
                            $countArray['TWaitQC_time']+=$row['test_status_time_diff'];
                            break;
                        case '16':
                            $countArray['AWaitQC_num']++;
                            $countArray['AWaitQC_time']+=$row['test_status_time_diff'];
                            break;
                        case '18':
                            $countArray['Arrival_num']++;
                            $countArray['Arrival_time']+=$row['test_status_time_diff'];
                            break;
                    }
                    //维修重要环节统计
                    if($row['receiving_start_time_diff']){//收货至质检
                        $countArray['arrival_to_receive_num']++;
                        $countArray['arrival_to_receive_time']+=$row['receiving_start_time_diff'];
                    }
                    //!in_array($row['status_id'],array(1,18,2,15)) &&
                    if($row['repair_start_time_diff']){//质检至接单维修
                        $countArray['receive_to_repair_num']++;
                        $countArray['receive_to_repair_time']+=$row['repair_start_time_diff'];
                    }
                    if($row['toQuote_quote_time_diff']){//待报价到已报价
                        $countArray['toQuote_to_quoteOk_num']++;
                        $countArray['toQuote_to_quoteOk_time']+=$row['toQuote_quote_time_diff'];
                    }
                    if($row['quote_ok_time_diff']){//确认报价
                        $countArray['quote_to_ok_num']++;
                        $countArray['quote_to_ok_time']+=$row['quote_ok_time_diff'];
                    }
                    if($row['await_parts_time_diff']){//等待配件
                        $countArray['await_to_parts_num']++;
                        $countArray['await_to_parts_time']+=$row['await_parts_time_diff'];
                    }
                    if($row['test_repairOk_time_diff']){//接单到维修完成
                        $countArray['receive_to_repairOk_num']++;
                        $countArray['receive_to_repairOk_time']+=$row['test_repairOk_time_diff'];
                    }
                    $countArray['TotalQuantity']++;//订单总量
                    $countArray['TotalTime']+=$row['test_status_time_diff'];//总耗时
                    $exportData[]=$row;
                }
            }else{
                break;
            }
            usleep(200);
        }
        unset($row);
        $returnData['brandArray']=$brandArray;
        $returnData['modelArray']=$modelArray;
        $returnData['faultDetailArray']=$faultDetailArray;
        $returnData['repairArray']=$repairArray;
        $returnData['partsArray']=$partsArray;
        $returnData['faultArray']=$faultArray;
        $returnData['countArray']=$countArray;
        $returnData['exportData']=$exportData;
        return $returnData;
    }

    /**
     * 重构产品轨迹
     * @param $pid
     * @param $addTime(当前状态时间)
     * @return array
     */
    public function StructureProductTrack($pid,$addTime){
        //产品轨迹数据
        $trackData=$this->reportModel->GetProductTrack($pid);
        $maxSid=$trackData[0]['end_sid'];
        //轨迹时间数据
        $data=array();
        //构建维修轨迹时间数据
        foreach($trackData as $row){
            switch($row['end_sid']){
                case '18':
                    //已收货
                    $data['receiving_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '2':
                    //检测完成待维修
                    $data['test_repair_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '3':
                    //接单(维修)
                    $data['their_repair_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '4':
                    //待报价
                    $data['to_quote_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '5':
                    //已报价
                    $data['quote_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '6':
                    //同意报价
                    $data['quote_ok_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '7':
                    //拒绝报价
                    $data['disagree_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '8':
                    //维修中_等待配件
                    $data['await_parts_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '9':
                    //维修中
                    $data['repair_ing_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '10':
                    //维修完成(移除检测失败，需要从新维修的情况)
                    if($maxSid >= 10) {
                        $data['repair_ok_time'] = date('Y-m-d H:i:s', $row['add_time']);
                    }
                    break;
                default :
                    continue;
                    break;
            }
        }
        //初始时间
        $start_s_time=$data['receiving_time']?$data['receiving_time']:$data['test_repair_time'];
        //报价时间：如果存在待报价取待报价没有取已报价
        //$quote_time=$data['to_quote_time']?$data['to_quote_time']:$data['quote_time'];
        //确认报价时间：如果存在拒绝报价取拒绝报价 没有取同意报价
        $quote_ok_time=$data['disagree_time']?$data['disagree_time']:$data['quote_ok_time'];
        //开始检测工作日
        if($data['receiving_time'] && $data['test_repair_time']) {
            $day_as=$this->GetWeekendDay($data['test_repair_time'],$data['receiving_time']);
            $data['receiving_start_time_diff'] = round((strtotime($data['test_repair_time']) - strtotime($data['receiving_time'])) / (3600 * 24),1)-$day_as;
        }else{
            if($data['receiving_time']) {
                $day_as_s = $this->GetWeekendDay(date('Y-m-d', time()), $data['receiving_time']);
                $data['receiving_start_time_diff'] = round((time() - strtotime($data['receiving_time'])) / (3600 * 24), 1) - $day_as_s;
            }
        }
        //开始维修工作日
        if($data['their_repair_time'] && $data['test_repair_time']) {
            //排除双休日
            $start_time=$data['receiving_time']?$data['receiving_time']:$data['test_repair_time'];
            $day_a=$this->GetWeekendDay($data['their_repair_time'],$start_time);
            $data['repair_start_time_diff'] = round((strtotime($data['their_repair_time']) - strtotime($data['test_repair_time'])) / (3600 * 24),1)-$day_a;
        }else{
            if($data['test_repair_time']) {
                $day_a_s = $this->GetWeekendDay(date('Y-m-d', time()), $data['test_repair_time']);
                $data['repair_start_time_diff'] = round((time() - strtotime($data['test_repair_time'])) / (3600 * 24), 1) - $day_a_s;
            }
        }
        //待报价到已报价处理工作日数
        if($data['quote_time'] && $data['to_quote_time']) {
            //排除双休日
            $day_b=$this->GetWeekendDay($data['quote_time'],$data['to_quote_time']);
            $data['toQuote_quote_time_diff'] = round((strtotime($data['quote_time']) - strtotime($data['to_quote_time'])) / (3600 * 24),1)-$day_b;
        }else{
            if($data['to_quote_time']) {
                $day_b_s = $this->GetWeekendDay(date('Y-m-d', time()), $data['to_quote_time']);
                $data['toQuote_quote_time_diff'] = round((time() - strtotime($data['to_quote_time'])) / (3600 * 24), 1) - $day_b_s;
            }
        }
        //确认报价工作日
        if($quote_ok_time && $data['quote_time']) {
            //排除双休日
            $day_c=$this->GetWeekendDay($quote_ok_time,$data['quote_time']);
            $data['quote_ok_time_diff']=round((strtotime($quote_ok_time)-strtotime($data['quote_time']))/(3600*24),1)-$day_c;
        }else{
            if($data['quote_time']) {
                $day_c_s = $this->GetWeekendDay(date('Y-m-d', time()), $data['quote_time']);
                $data['quote_ok_time_diff'] = round((time() - strtotime($data['quote_time'])) / (3600 * 24), 1) - $day_c_s;
            }
        }
        //等待配件工作日
        if($data['repair_ing_time'] && $data['await_parts_time']) {
            //排除双休日
            $day_d=$this->GetWeekendDay($data['repair_ing_time'],$data['await_parts_time']);
            $data['await_parts_time_diff']=round((strtotime($data['repair_ing_time'])-strtotime($data['await_parts_time']))/(3600*24),1)-$day_d;
        }else{
            if($data['await_parts_time']) {
                $day_d_s = $this->GetWeekendDay(date('Y-m-d', time()), $data['await_parts_time']);
                $data['await_parts_time_diff'] = round((time() - strtotime($data['await_parts_time'])) / (3600 * 24), 1) - $day_d_s;
            }
        }
        //接单到维修完成工作日
        if($data['repair_ok_time'] && $data['test_repair_time']) {
            //排除双休日
            $day_e=$this->GetWeekendDay($data['repair_ok_time'],$data['test_repair_time']);
            $data['test_repairOk_time_diff']=round((strtotime($data['repair_ok_time'])-strtotime($data['test_repair_time']))/(3600*24),1)-$day_e;
        }else{
            $data['test_repairOk_time_diff']=0;
        }
        //接单到当前状态工作日
        if($addTime && $start_s_time) {
            //排除双休日
            $day_f=$this->GetWeekendDay(date('Y-m-d',$addTime),$start_s_time);
            $data['test_status_time_diff']=round(($addTime-strtotime($start_s_time))/(3600*24),1)-$day_f;
        }else{
            $data['test_status_time_diff']=0;
        }
        //如果最终状态为同意报价 则等待配件的时间为：同意报价至当今工作日
        if($maxSid==6){
            $day_j_s = $this->GetWeekendDay(date('Y-m-d', time()), $data['quote_ok_time']);
            $data['await_parts_time_diff'] = round((time() - strtotime($data['quote_ok_time'])) / (3600 * 24), 1) - $day_j_s;
        }
        return $data;
    }

    /**
     * 获取双休日量
     * @param string $day_max
     * @param string $day_min
     * @return int
     */
    public function GetWeekendDay($day_max='',$day_min=''){
        $s=0;
        $day_max=explode(' ',$day_max);
        $day_max=strtotime($day_max[0]);
        $day_min=explode(' ',$day_min);
        $day_min=strtotime($day_min[0]);
        if($day_max && $day_min) {
            $day_time = 3600 * 24;
            $day_diff = ceil(($day_max - $day_min) / $day_time);
            for ($i = 0; $i <= $day_diff; $i++) {
                $day_w = date('w', $day_min + $i * $day_time);
                if ($day_w == 0 || $day_w == 6) {
                    $s++;
                }
            }
        }
        return $s;
    }

    /**
     * 初始化统计数组(防止后期可能会有特殊初始值，做封装处理)
     * @return array
     */
    public function InitCountArray(){
        $countArray=array(
            //总量
            'TotalQuantity'=>0,
            'TotalTime'=>0,
            //综合数据
            'WaitReceive_num'=>0,//待接单
            'WaitReceive_time'=>'暂无',//待接单时长
            'RepairIng_num'=>0,//维修中量
            'RepairIng_time'=>0,//维修中时长
            'RepairOK_num'=>0,//维修完成量
            'RepairOK_time'=>0,//维修完成时长
            //维修中详细数据_数量
            'TestRepair_num'=>0,
            'RepairAssigned_num'=>0,
            'WaitQuote_num'=>0,
            'PriceQuoted_num'=>0,
            'Agree_num'=>0,
            'Disagree_num'=>0,
            'WaitParts_num'=>0,
            'Repairing_num'=>0,
            'RWaitQC_num'=>0,
            'QC_num'=>0,
            'WaitInStock_num'=>0,
            'WaitShip_num'=>0,
            'TWaitQC_num'=>0,
            'AWaitQC_num'=>0,
            'Arrival_num'=>0,
            //维修中详细数据_工作日数
            'TestRepair_time'=>0,
            'RepairAssigned_time'=>0,
            'WaitQuote_time'=>0,
            'PriceQuoted_time'=>0,
            'Agree_time'=>0,
            'Disagree_time'=>0,
            'WaitParts_time'=>0,
            'Repairing_time'=>0,
            'RWaitQC_time'=>0,
            'QC_time'=>0,
            'WaitInStock_time'=>0,
            'WaitShip_time'=>0,
            'TWaitQC_time'=>0,
            'AWaitQC_time'=>0,
            'Arrival_time'=>0,
            //维修中重要数据_数量
            'receive_to_repair_num'=>0,
            'toQuote_to_quoteOk_num'=>0,
            'quote_to_ok_num'=>0,
            'await_to_parts_num'=>0,
            'receive_to_repairOk_num'=>0,
            //维修中重要数据_工作日数
            'receive_to_repair_time'=>0,
            'toQuote_to_quoteOk_time'=>0,
            'quote_to_ok_time'=>0,
            'await_to_parts_time'=>0,
            'receive_to_repairOk_time'=>0,
        );
        return $countArray;
    }

    /**
     * 生成维修报告数据
     * @param $data
     * @return array
     */
    public function CreateServiceReportData($data){
        //总数量
        $total=$data['TotalQuantity'];//总量
        $wrTotal=$data['WaitReceive_num'];//待接单量
        $riTotal=$data['RepairIng_num'];//维修中量
        $roTotal=$data['RepairOK_num'];//维修完成量
        //总耗时
        $totalTime=$data['TotalTime'];//总耗时
        $wrTotalTime=$data['WaitReceive_time'];//待接单总时长
        $riTotalTime=$data['RepairIng_time'];//维修中总时长
        $roTotalTime=$data['RepairOK_time'];//维修完成总时长
        //拼接字符串
        $toStr=$total.'单 占比100% 平均工作历时:'.round($totalTime/$total,1);
        $wrStr=$wrTotal.'单 占比'.round((($wrTotal/$total)*100),2).'% 平均工作历时:'.$wrTotalTime;
        $riStr=$riTotal.'单 占比'.round((($riTotal/$total)*100),2).'% 平均工作历时:'.round(($riTotalTime/$riTotal),1);
        $roStr=$roTotal.'单 占比'.round((($roTotal/$total)*100),2).'% 平均工作历时:'.round(($roTotalTime/$roTotal),1);
        //生成数据
        $rData=array(
            array($wrStr,$riStr,$roStr,$toStr),
            array('维修中状态','数量','占比','平均历时(工作日)'),
            array('已收货',$data['Arrival_num'],round((($data['Arrival_num']/$riTotal)*100),2).'%',round(($data['Arrival_time']/$data['Arrival_num']),1)),
            array('检测完成_待维修',$data['TestRepair_num'],round((($data['TestRepair_num']/$riTotal)*100),2).'%',round(($data['TestRepair_time']/$data['TestRepair_num']),1)),
            array('接单(维修)',$data['RepairAssigned_num'],round((($data['RepairAssigned_num']/$riTotal)*100),2).'%',round(($data['RepairAssigned_time']/$data['RepairAssigned_num']),1)),
            array('待报价',$data['WaitQuote_num'],round((($data['WaitQuote_num']/$riTotal)*100),2).'%',round(($data['WaitQuote_time']/$data['WaitQuote_num']),1)),
            array('已报价',$data['PriceQuoted_num'],round((($data['PriceQuoted_num']/$riTotal)*100),2).'%',round(($data['PriceQuoted_time']/$data['PriceQuoted_num']),1)),
            array('同意报价',$data['Agree_num'],round((($data['Agree_num']/$riTotal)*100),2).'%',round(($data['Agree_time']/$data['Agree_num']),1)),
            array('拒绝报价',$data['Disagree_num'],round((($data['Disagree_num']/$riTotal)*100),2).'%',round(($data['Disagree_time']/$data['Disagree_num']),1)),
            array('维修中_等待配件',$data['WaitParts_num'],round((($data['WaitParts_num']/$riTotal)*100),2).'%',round(($data['WaitParts_time']/$data['WaitParts_num']),1)),
            array('维修中',$data['Repairing_num'],round((($data['Repairing_num']/$riTotal)*100),2).'%',round(($data['Repairing_time']/$data['Repairing_num']),1)),
            array('维修完成_待QC',$data['RWaitQC_num'],round((($data['RWaitQC_num']/$riTotal)*100),2).'%',round(($data['RWaitQC_time']/$data['RWaitQC_num']),1)),
            array('接单(质检)',$data['QC_num'],round((($data['QC_num']/$riTotal)*100),2).'%',round(($data['QC_time']/$data['QC_num']),1)),
            array('检测完成_待入库',$data['WaitInStock_num'],round((($data['WaitInStock_num']/$riTotalTime)*100),2).'%',round(($data['WaitInStock_time']/$data['WaitInStock_num']),1)),
            array('待发货',$data['WaitShip_num'],round((($data['WaitShip_num']/$riTotal)*100),2).'%',round(($data['WaitShip_time']/$data['WaitShip_num']),1)),
            array('检测完成_待QC',$data['TWaitQC_num'],round((($data['TWaitQC_num']/$riTotal)*100),2).'%',round(($data['TWaitQC_time']/$data['TWaitQC_num']),1)),
            array('装配完成_待QC',$data['AWaitQC_num'],round((($data['AWaitQC_num']/$riTotal)*100),2).'%',round(($data['AWaitQC_time']/$data['AWaitQC_num']),1)),
            array('合计',$riTotal,'100%',round(($riTotalTime/$riTotal),1)),
            array('维修中重要环节','平均历时(工作日)','评估','解决方案'),
            array('已收货至检测完成待维修',round(($data['arrival_to_receive_time']/$data['arrival_to_receive_num']),1),'',''),
            array('检测完成待维修至接单维修',round(($data['receive_to_repair_time']/$data['receive_to_repair_num']),1),'',''),
            array('待报价到已报价处理工作日数',round(($data['toQuote_to_quoteOk_time']/$data['toQuote_to_quoteOk_num']),1),'',''),
            array('确认报价工作日数',round(($data['quote_to_ok_time']/$data['quote_to_ok_num']),1),'',''),
            array('等待配件',round(($data['await_to_parts_time']/$data['await_to_parts_num']),1),'',''),
            array('接单到完成维修',round(($data['receive_to_repairOk_time']/$data['receive_to_repairOk_num']),1),'',''),
            array('接单到流程结束',round(($roTotalTime/$roTotal),1),'',''),
        );
        return $rData;
    }

    /**
     * 生成维修项明细数据
     * @param $data
     * @return array
     */
    public function CreateBrandDetailData($data){
        $rData=array();
        $total=$data['total'];
        unset($data['total']);
        //重构数据
        foreach($data as $key=>$val){
            $refactor=array();
            $refactor['brand']=$key;
            foreach($val as $k=>$v){
                $refactor['warrantyType']=$k;
                foreach($v as $minK=>$minV){
                    $refactor['model']=$minK;
                    $refactor['num']=$minV['num'];
                    $refactor['rate']=$minV['num']/$total;
                    $refactor['repairItem' . $k] = implode('#', $minV['repairItem']);
                    $rData[]=$refactor;
                }
            }
        }
        return $rData;
    }

    /**
     * 生成故障项明细数据
     * @param $data
     * @return array
     */
    public function CreateFaultDetailData($data){
        $rData=array();
        $total=$data['total'];
        unset($data['total']);
        //重构数据
        foreach($data as $key=>$val){
            $refactor=array();
            $refactor['brand']=$key;
            foreach($val as $k=>$v){
                $refactor['warrantyType']=$k;
                foreach($v as $minK=>$minV){
                    $refactor['model']=$minK;
                    $refactor['num']=$minV['num'];
                    $refactor['rate']=$minV['num']/$total;
                    $refactor['fault' . $k] = implode('#', $minV['fault']);
                    $rData[]=$refactor;
                }
            }
        }
        return $rData;
    }
    /**
     * 生成品牌比例数据
     * @param $data
     * @return array
     */
    public function CreateBrandRateData($data){
        $rData[]=array();
        $total=$data['total'];
        unset($data['total']);
        //重构数据
        foreach($data as $key=>$val){
            $refactor=array();
            $refactor['totalNum']=$val['Y']['num']+$val['N']['num'];
            $refactor['brand']=$key;
            $refactor['totalRate']=round($refactor['totalNum']/$total*100,2).'%';
            $refactor['yNum']=$val['Y']['num']?:0;
            $refactor['yRate']=round($refactor['yNum']/$refactor['totalNum']*100,2).'%';
            $refactor['nNum']=$val['N']['num']?:0;
            $refactor['nRate']=round($refactor['nNum']/$refactor['totalNum']*100,2).'%';
            $refactor['repairItem']=implode('#',array_merge($val['Y']['repairItem']?:array(),$val['N']['repairItem']?:array()));
            $rData[]=$refactor;
        }
        return $rData;
    }

    /**
     * 生成维修项比例数据(虽然现在和下面的统计方式一样，但千万不要几个函数合并，防止后期不一样)
     * @param $data
     * @return array
     */
    public function CreateRepairItemData($data){
        $rData=array();
        foreach($data as $key=>$val){
            $refactor=array();
            $refactor['model']=$key;
            $total=$val['total'];
            unset($val['total']);
            foreach($val as $row){
                $refactor['repairName'] = $row['name'];
                $refactor['num'] = $row['num'];
                $refactor['rate'] = round(($row['num']/$total)*100,2).'%';
                $rData[]=$refactor;
            }
        }
        return $rData;
    }

    /**
     * 生成配件比例数据
     * @param $data
     * @return array
     */
    public function CreatePartsRateData($data){
        $rData=array();
        foreach($data as $key=>$val){
            $refactor=array();
            $refactor['model']=$key;
            $total=$val['total'];
            unset($val['total']);
            foreach($val as $row){
                $refactor['partsName'] = $row['name'];
                $refactor['num'] = $row['num'];
                $refactor['rate'] = round(($row['num']/$total)*100,2).'%';
                $rData[]=$refactor;
            }
        }
        return $rData;
    }

    /**
     * 生成配件比例数据
     * @param $data
     * @return array
     */
    public function CreateFaultRateData($data){
        $rData=array();
        foreach($data as $key=>$val){
            $refactor=array();
            $refactor['model']=$key;
            $total=$val['total'];
            unset($val['total']);
            foreach($val as $row){
                $refactor['faultName'] = $row['name'];
                $refactor['num'] = $row['num'];
                $refactor['rate'] = round(($row['num']/$total)*100,2).'%';
                $rData[]=$refactor;
            }
        }
        return $rData;
    }
    //-----------------------------------------------------------旧数据-------------------------------------
    /**
     * 重构旧产品轨迹数据
     * @param $order_num
     * @param $add_time
     * @return array
     */
    public function StructureProductOldTrack($order_num,$add_time){
        $trackData=$this->reportModel->GetOldTrack($order_num);
        $data=array();
        foreach($trackData as $row){
            switch($row['target_status']){
                case '2':
                    $data['test_wait_time']=$row['add_time'];
                    break;
                case '3':
                    $data['accept_order_time']=$row['add_time'];
                    break;
                case '4':
                    $data['quoted_ok_time']=$row['add_time'];
                    break;
                case '5':
                    $data['quoted_confirm_time']=$row['add_time'];
                    break;
                case '6':
                    $data['repair_ing_time']=$row['add_time'];
                    break;
                case '7':
                    $data['waiting_parts_time']=$row['add_time'];
                    break;
                case '8':
                    $data['repair_complete_time']=$row['add_time'];
                    break;
                case '23':
                    $data['quoted_confirm_time']=$row['add_time'];
                    break;
                case '24':
                    $data['quoted_confirm_time']=$row['add_time'];
                    break;
                default :
                    continue;
                    break;
            }
        }
        //收到到开始维修
        if($data['accept_order_time'] && $data['test_wait_time']){
            $day_a=$this->GetWeekendDay($data['accept_order_time'],$data['test_wait_time']);
            $data['repair_start_time_diff']=round((strtotime($data['accept_order_time'])-strtotime($data['test_wait_time']))/(24*3600),1)-$day_a;
        }else{
            $data['repair_start_time_diff']=0;
        }
        //接单到报价
        if($data['quoted_ok_time'] && $data['accept_order_time']){
            $day_b=$this->GetWeekendDay($data['quoted_ok_time'],$data['accept_order_time']);
            $data['accept_quoted_time_diff']=round((strtotime($data['quoted_ok_time'])-strtotime($data['accept_order_time']))/(24*3600),1)-$day_b;
        }else{
            $data['accept_quoted_time_diff']=0;
        }
        //同意报价
        if($data['quoted_confirm_time'] && $data['quoted_ok_time']){
            $day_c=$this->GetWeekendDay($data['quoted_confirm_time'],$data['quoted_ok_time']);
            $data['confirm_quoted_time_diff']=round((strtotime($data['quoted_confirm_time'])-strtotime($data['quoted_ok_time']))/(24*3600),1)-$day_c;
        }else{
            $data['confirm_quoted_time_diff']=0;
        }
        //等待配件
        if($data['waiting_parts_time'] && $data['quoted_confirm_time']){
            $day_d=$this->GetWeekendDay($data['waiting_parts_time'],$data['quoted_confirm_time']);
            $data['waiting_parts_time_diff']=round((strtotime($data['waiting_parts_time'])-strtotime($data['quoted_confirm_time']))/(24*3600),1)-$day_d;
        }else{
            $data['waiting_parts_time_diff']=0;
        }
        //收到到维修完成
        if($data['repair_complete_time'] && $data['test_wait_time']){
            $day_e=$this->GetWeekendDay($data['repair_complete_time'],$data['test_wait_time']);
            $data['repair_complete_time_diff']=round((strtotime($data['repair_complete_time'])-strtotime($data['test_wait_time']))/(24*3600),1)-$day_e;
        }else{
            $data['repair_complete_time_diff']=0;
        }
        //接单到当前状态
        if($add_time && $data['test_wait_time']){
            $day_f=$this->GetWeekendDay($add_time,$data['test_wait_time']);
            $data['repair_now_time_diff']=round((strtotime($add_time)-strtotime($data['test_wait_time']))/(24*3600),1)-$day_f;
        }else{
            $data['repair_now_time_diff']=0;
        }
        return $data;
    }

    /**
     * 获取商家旧数据
     * @param string $email
     * @param string $point
     * @param string $sTime
     * @param string $nTime
     */
    public function GetMerchantOrderOldData($email='',$point='',$sTime='',$nTime=''){
        $data = $this->reportModel->GetOldProductEmail($email,$point,$sTime,$nTime);
        $warrantyType = array('保外', '保内','品牌保内');//小数据导出用的 避开查表
        $repairType=array('6'=>'维修','7'=>'翻新','8'=>'退货','9'=>'递四方检查单','10'=>'返修');
        $pointType=array('1'=>'西班牙','2'=>'俄罗斯','3'=>'德国','4'=>'英国','5'=>'美国','6'=>'深圳');
        foreach($data as &$row){
            $trackData=$this->StructureProductOldTrack($row['maintain_id'],$row['add_time']);
            $itemData=$this->reportModel->GetOldItem($row['product_id']);
            //gsh_output($itemData);
            $partsData=$this->reportModel->GetOldPartsTwo($row['product_id']);
            $row['itemStr']=$itemData['str'];
            $row['partsStr']=$partsData['str'];
            $row['repair_start_time_diff']=$trackData['repair_start_time_diff']>=0?$trackData['repair_start_time_diff']:0;
            $row['accept_quoted_time_diff']=$trackData['accept_quoted_time_diff']>=0?$trackData['accept_quoted_time_diff']:0;
            $row['confirm_quoted_time_diff']=$trackData['confirm_quoted_time_diff']>=0?$trackData['confirm_quoted_time_diff']:0;
            $row['waiting_parts_time_diff']=$trackData['waiting_parts_time_diff']>=0?$trackData['waiting_parts_time_diff']:0;
            $row['repair_complete_time_diff']=$trackData['repair_complete_time_diff']>=0?$trackData['repair_complete_time_diff']:0;
            $row['repair_now_time_diff']=$trackData['repair_now_time_diff']>=0?$trackData['repair_now_time_diff']:0;
            $row['is_guarantee']=$warrantyType[$row['is_guarantee']];
            $row['maintain_type_id']=$repairType[$row['maintain_type_id']];
            $row['status_id']=$this->reportModel->GetOldTrackName($row['status_id']);

            $row['repair_site_id']=$pointType[$row['repair_site_id']];
        }
        unset($row);
        return $data;
    }

    /**
     * 导出旧数据
     */
    public function ExportOldData(){
        $data=$this->GetMerchantOrderOldData('liulu@aukeys.com');
        $fieldData=array(
            'maintain_id'=>'订单号',
            'consumer_email'=>'客户邮箱',
            'repair_site_id'=>'站点',
            'maintain_type_id'=>'维修类型',
            'brand_name'=>'产品品牌',
            'product_model'=>'型号',
            'enter_time'=>'建单时间',
            'repair_start_time_diff'=>'收到到开始维修工作日数',
            'accept_quoted_time_diff'=>'接单到报价历经工作日',
            'confirm_quoted_time_diff'=>'同意报价工作日数',
            'waiting_parts_time_diff'=>'等待配件工作日数',
            'repair_complete_time_diff'=>'接收到维修完成工作日数',
            'repair_now_time_diff'=>'接单到当前状态工作日数',
            'status_id'=>'当前状态',
            'itemStr'=>'维修项',
            'partsStr'=>'配件项',
            'is_guarantee'=>'质保类型',
        );
        excel_output('dataFuck',$fieldData,$data);
    }
    //----------------------------------------------------维修KPI--------------------------------------
    /**
     * 获取维修师KPI数据（关联太多表，部分表避开查询，采用数组形式）
     * @return array
     */
    public function getRepairPeopleKPI(){
        $gp=gp();
        $data=array();//KPI数据
        $yzNew=array();//验证数据（判断是否存在返修的情况）
        $yzOld=array();//验证数据（判断是否存在返修的情况）
        $site=array('1'=>'es','2'=>'ru','3'=>'de','4'=>'uk','5'=>'us','6'=>'sz');//站点
        $service_type_old=array('6'=>'维修','7'=>'翻新','8'=>'退货','9'=>'递四方检测单','10'=>'返修');//旧维修类型
        $service_type_new=array('1'=>'维修','2'=>'退货','3'=>'翻新','4'=>'返修','5'=>'检测','6'=>'购买配件');
        $status_new=array('10'=>'维修完成_待QC','11'=>'接单(质检)','12'=>'检测完成_待入库','13'=>'入库完成','14'=>'待发货','15'=>'检测完成_待QC','16'=>'装配完成_待QC','17'=>'已发货');
        $status_old=array('8'=>'维修完成','9'=>'出库质检','10'=>'已发货','11'=>'结束，评价','21'=>'检测完成_待入库','22'=>'入库完成','26'=>'检测完成_待QC','27'=>'装配完成_待QC');
        $type_old=array('1'=>6,'2'=>10);//订单类型 旧
        $type_new=array('1'=>1,'2'=>4);//订单类型 新
        //构建KPI数据 新
        $dataNew=$this->reportModel->getRepairPeopleKPINew($gp['repairPeople'],'',strtotime($gp['startTime']),strtotime($gp['endTime']));
        foreach($dataNew as $row){
            $yzNew[$row['id']][$row['end_sid']]++;
            if($yzNew[$row['id']][$row['end_sid']] <= 1){
                $repairItem=$this->reportModel->GetRepairItemStr($row['repairItem']);
                $NAQAmount=$row['NAQAmount'];
                $naq=$this->common_model->selectFirst('mt_product_track',array('pid'=>$row['id'],'end_sid'=>7));
                if($naq){
                    $laborAmount=$NAQAmount;
                }else {
                    $laborAmount = $row['laborAmountIndividualUser'] + $row['laborAmountMerchant'] + $row['laborAmountBrand'] + $row['ruLaborAmountIndividualUser'] + $row['supplementLaborAmount'];
                }
                $data[]=array(
                    'add_time'=>date('Y-m-d H:i:s',$row['add_time']),
                    'point'=>$row['point'],
                    'order_num'=>$row['order_num'],
                    'service_type'=>$service_type_new[$row['service_type']],
                    'pid'=>$row['id'],
                    'model'=>$row['product_model'],
                    'repairItem'=>$repairItem['str'],
                    'repairName'=>$row['add_user'],
                    'laborAmount'=>$laborAmount,
                    'kpi'=>round($laborAmount/12,3),
                    'status'=>$status_new[$row['status_id']]
                );
            }
        }
        //构建KPI数据 旧
        $dataOld=$this->reportModel->getRepairPeopleKPIOld($gp['repairPeople'],'',strtotime($gp['startTime']),strtotime($gp['endTime']));
        foreach($dataOld as $row2){
            $yzOld[$row2['product_id']][$row2['target_status']]++;
            if($yzOld[$row2['product_id']][$row2['target_status']] <= 1){
                $naq=$this->common_model->selectFirst('maintain_track',array('maintain_id'=>$row2['maintain_id'],'target_status'=>24));
                if($naq) {
                    $laborAmount = $row2['total_for_not_accepted'];
                }else{
                    $laborAmount = $row2['service_fee'] + $row2['maintain_price'];
                }
                $repairItem=$this->reportModel->getItemOld($row2['maintain_id']);
                $data[]=array(
                    'add_time'=>$row2['add_time'],
                    'point'=>$site[$row2['repair_site_id']],
                    'order_num'=>$row2['maintain_id'],
                    'service_type'=>$service_type_old[$row2['maintain_type_id']],
                    'pid'=>$row2['product_id'],
                    'model'=>$row2['product_model'],
                    'repairItem'=>$repairItem,
                    'repairName'=>$row2['modified_user'],
                    'laborAmount'=>$laborAmount,
                    'kpi'=>round($laborAmount/12,3),
                    'status'=>$status_old[$row2['status_id']]
                );
            }
        }
        $fieldData=array(
            'add_time'=>'日期',
            'point'=>'站点',
            'order_num'=>'订单号',
            'service_type'=>'维修类型',
            'pid'=>'产品编号',
            'model'=>'产品型号',
            'repairName'=>'维修师',
            'laborAmount'=>'手工费',
            'repairItem'=>'维修项',
            'kpi'=>'kpi',
            'status'=>'当前状态',
        );
        excel_output('repairKpi',$fieldData,$data);
    }

    /**
     * 获取KPI
     */
    public function getKpi(){
        $gp=gp();
        $kpiData=array();
        $retData=array();
        //账户类型状态值
        $roleStatus=array(6=>array(11),4=>array(2,15),9=>array(13,17),3=>array(18));
        //账户类型KPI值
        $roleKpi=array(6=>0.325,4=>0.275,9=>0.1,3=>0.08);
        //账户类型角色名
        $roleName=array(6=>'出库质检员',4=>'拆包质检员',9=>'发货员',3=>'收货员');
        $service_type_old=array('6'=>'维修','7'=>'翻新','8'=>'退货','9'=>'递四方检测单','10'=>'返修');//旧维修类型
        $service_type_new=array('1'=>'维修','2'=>'退货','3'=>'翻新','4'=>'返修','5'=>'检测','6'=>'购买配件');
        $trackData=$this->reportModel->getTrack($gp['id'],$roleStatus[$gp['type']],strtotime($gp['startTime']),strtotime($gp['endTime']));
        foreach($trackData as $row){
            $retData[$row['pid']][$row['end_sid']] += 1;//对反复操作同一轨迹进行计数
            if ($retData[$row['pid']][$row['end_sid']] <= 1) {//验证是否重复操作
                $productInfo=$this->reportModel->getProductInfo($row['pid']);
                $productInfo['kpi']=$roleKpi[$gp['type']];
                $productInfo['add_time']= date('Y-m-d',$productInfo['add_time']);
                $productInfo['add_user']=$row['add_user'];
                $productInfo['service_type']=$service_type_new[$productInfo['service_type']];
                $kpiData[]=$productInfo;
            }
        }
        $fieldData=array(
            'add_time'=>'日期',
            'point'=>'站点',
            'order_num'=>'订单号',
            'service_type'=>'维修类型',
            'id'=>'产品编号',
            'product_model'=>'产品型号',
            'add_user'=>$roleName[$gp['type']],
            'kpi'=>'kpi',
            'name_ch'=>'当前状态',
        );
        excel_output('kpiData',$fieldData,$kpiData);
    }

    /**
     * 导出hold订单
     */
    public function exportHoldOrder(){
        $gp=gp();
        $data=$this->reportModel->getHoldOrder($gp['merchant_num'],$gp['startTime'],$gp['endTime']);
        foreach($data as &$row){
            $merchantData=$this->common_model->selectFirst('mt_customers',array('id'=>$row['merchant_num']));
            $statusData=$this->common_model->selectFirst('mt_product_status',array('id'=>$row['status_id']));
            $remarkData=$this->common_model->selectFirst('mt_product_log',array('pid'=>$row['id']));
            if($remarkData['content']) {
                $contentJson = json_decode($remarkData['content'], true);
                $content =$contentJson['otherRemark'];
            }else{
                $content='手动hold:原因不详';
            }
            $row['merchant_name']=$merchantData['name'];
            $row['status_name']=$statusData['name_ch'];
            $row['add_time']=date('Y-m-d H:i:s',$row['add_time']);
            if($row['inWarranty']==='' || $row['inWarranty_qc']===''){
                $row['remark']=$content;
            }else{
                if($row['inWarranty'] != $row['seller_warranty'] || $row['inWarranty_qc'] != $row['seller_warranty']){
                    $row['remark']='质保类型不一致导致hold';
                }else{
                    $row['remark']='余额不足导致hold';
                }
            }
        }
        unset($row);
        $fieldData=array(
            'order_num'=>'维修单号',
            'merchant_name'=>'所属部门平台',
            'status_name'=>'维修状态',
            'add_time'=>'最新更新日期',
            'remark'=>'hold的原因',
        );
        excel_output('holdOrder',$fieldData,$data);
    }

    /**
     * 导出EXCEL
     * @param $data
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    public function ExportExcel($data){
        //加载excel类
        $this->load->library('excel/PHPExcel');
        //设定缓存模式为经gzip压缩后存入cache
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
        $excel=new PHPExcel();
        //如果每个sheet都要求导出不同格式 就要摒弃循环  单个处理
        foreach($data as $rowKey=>$rowVal){
            //将标题添加到数组中
            array_unshift($rowVal['infoData'],$rowVal['fieldData']);
            //创建一个新的工作空间(sheet)
            if($rowKey) {
                $excel->createSheet();
            }
            $excel->setactivesheetindex($rowKey);
            $excel->getActiveSheet()->setTitle($rowVal['sheet']);
            $letter='A';
            foreach ($rowVal['fieldData'] as $key=>$val) {
                foreach ($rowVal['infoData'] as $k=>$rs) {
                    $excel->getActiveSheet()->setCellValue($letter.($k+1),$rs[$key]);
                }
                $letter++;
            }
        }
        ob_end_clean();
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header("Content-Disposition:attachment;filename='dataAnalysis.xls'");
        header('Content-Transfer-Encoding:binary');
        $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $objWriter->save('php://output');
    }

    /**
     * 获取对人民币汇率
     * @param $currency
     * @return mixed
     */
    function getRate($currency){
        $data['USD']=6.7923;
        $data['CNY']=1;
        $data['EUR']=7.7283;
        $data['RUB']=0.1143;
        $data['GBP']=8.8111;
        return $data[$currency];
    }
}